package com.prince.web.service.impl;

import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.constant.Constants;
import com.prince.entity.InventoryVo;
import com.prince.enums.SaleEnum;
import com.prince.mapper.InventoryMapper;
import com.prince.mapper.ProcurementMapper;
import com.prince.mapper.x.InventoryMapperX;
import com.prince.model.Inventory;
import com.prince.model.Procurement;
import com.prince.page.Page;
import com.prince.util.MD5Util;
import com.prince.util.MapUtil;
import com.prince.web.service.InventoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: 库存
 *
 * @Author: 王培喜 58528792@163.com
 * @Date: 2021/4/6 14:58
 */
@Service
public class InventoryServiceImpl implements InventoryService {

    @Resource
    private InventoryMapperX inventoryMapperX;
    @Resource
    private InventoryMapper inventoryMapper;
    @Resource
    private ProcurementMapper procurementMapper;

    /**
     * 功能描述: 分页查询库存
     *
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 15:25
     */
    @Override
    public Map<String, Object> findInventoryByPage(Map<String, Object> params, Page page) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        if(MapUtil.isNotEmpty(params,"name")){
            params.put("name","%"+params.get("name")+"%");
        }
        if(MapUtil.isNotEmpty(params,"supplier")){
            params.put("supplier","%"+params.get("supplier")+"%");
        }

        if(null != page){
            params.put("page",page.getBegin());
            params.put("rows",page.getLength());
        }
        List<InventoryVo> list = inventoryMapperX.selectByConditions(params);
        int total = inventoryMapperX.countByConditions(params);
        return response.toHashMapByPage(total, list);
    }

    /**
     * 功能描述: 添加库存
     *
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    @Transactional
    public Map<String, Object> addInventoryNumber(Integer id, BigDecimal number, String name) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        try {
            if(null == id || null == number){
                return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.parameterNull).toHashMap();
            }
            //入库数量必须大于0
            if(!(number.doubleValue() > 0)){
                return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.GT_NUMBER).toHashMap();
            }
            //添加库存
            updateInventory(id,number,name, SaleEnum.ADD);
        }catch (Exception e){
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //退货失败
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.saveError).toHashMap();
        }
        return response.toHashMap();
    }

    private void updateInventory(Integer id, BigDecimal number, String name, SaleEnum fundDirectionEnum) throws Exception{
        Inventory inventory = inventoryMapper.selectByPrimaryKey(id);
        //添加采购记录
        Procurement procurement = new Procurement();
        procurement.setCreater(name);
        procurement.setDel(Constants.YES);
        procurement.setCreated(new Date());
        procurement.setUpdater(name);
        procurement.setNumber(number);
        procurement.setProductId(inventory.getProductId());
        procurement.setDirection(fundDirectionEnum.getCode());
        int i = procurementMapper.insertSelective(procurement);
        if (i < 1) {
            //抛异常
            throw new Exception();
        }
        BigDecimal source = null;
        if(SaleEnum.ADD.getCode().equals(fundDirectionEnum.getCode())){
            //添加库存
            source = inventory.getNumber().add(number);
        }else{
            //减少库存
            source = inventory.getNumber().subtract(number);
            if(source.doubleValue() < 0){
                throw  new Exception();
            }
        }
        String key = Constants.USER + inventory.getProductId() + source;
        key = MD5Util.encrypt(key);
        // 更新库存表 库存增加
        i = inventoryMapperX.updateInventoryNumber(source, key, inventory.getId(), inventory.getMd5key(),name);
        if (i < 1) {
            //抛异常
            throw new Exception();
        }
        }
    /**
     * 功能描述: 库存退货
     *
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    @Transactional
    public Map<String, Object> inventoryReturnNumber(Integer id, BigDecimal number, String name) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        try {
            if(null == id || null == number){
                return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.parameterNull).toHashMap();
            }
            //退货数量必须大于0
            if(!(number.doubleValue() > 0)){
                return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.GT_NUMBER).toHashMap();
            }
            //较少库存
            updateInventory(id,number,name, SaleEnum.SUBTRACT);
        } catch (Exception e) {
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //退货失败
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.returnError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 变更库存状态
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/12 16:01
     */
    @Override
    public Map<String, Object> updateInventoryStatus(Inventory inventory) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        int i = inventoryMapper.updateByPrimaryKeySelective(inventory);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.updateError).toHashMap();
        }
        return response.toHashMap();
    }

    /**
     * 功能描述: 采购记录
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 15:25
     */
    @Override
    public Map<String, Object> findProcurementByPage(Map<String, Object> params, Page page) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        if(MapUtil.isNotEmpty(params,"name")){
            params.put("name","%"+params.get("name")+"%");
        }
        if(MapUtil.isNotEmpty(params,"supplier")){
            params.put("supplier","%"+params.get("supplier")+"%");
        }
        if(null != page){
            params.put("page",page.getBegin());
            params.put("rows",page.getLength());
        }
        List<InventoryVo> list = inventoryMapperX.selectProcurementByConditions(params);
        int total = inventoryMapperX.countProcurementByConditions(params);
        return response.toHashMapByPage(total, list);
    }

}
